//1 声明变量用来缓存组件对象
var logDatagrid;
$(function(){
  //2 使用声明的变量来缓存组件
  logDatagrid=$("#logDatagrid");

  //3 创建一个命令对象，存放所有的按钮的点击事件的回调
  cmdObj={
    deleteSelected:function () {
      var rows = logDatagrid.datagrid("getSelections");
      var postArray = [];
      for(var i = 0;i<rows.length;i++){
        console.debug(rows[i].id);
        postArray[i]=(rows[i].id);
      }

      //console.debug(rows);
      if(rows.length==0){
        $.messager.alert("提示","请选择要删除的数据","info");
        return;
      }
      $.messager.confirm("提示","确认删除选择吗？",function (r) {
        //var str = JSON.stringify(row1);
        if(r){
          $.get("log/delete?data="+postArray.toString() ,function (result) {
            if(result.success){
              $.messager.alert("提示","删除成功","info");
              logDatagrid.datagrid("reload");
            }else{
              $.messager.alert("提示","删除失败，原因为"+result.message,"info");
            }
          },"json")
        }
      });
    },
    deleteAll:function () {
      $.messager.confirm("提示","确认删除所有？",function (r) {
        if(r){
          $.get("log/deleteAll",{},function (result) {
            if(result.success){
              $.messager.alert("提示","删除成功","info");
              logDatagrid.datagrid("reload");
            }else{
              $.messager.alert("提示","删除失败，原因为"+result.message,"info");
            }
          },"json")
        }
      });
    },
    refresh:function () {
      logDatagrid.datagrid("reload");
    },
    selectAll:function () {
      var rows = logDatagrid.datagrid("getSelections");
      console.debug(rows);
      if(rows.length==0) {
        logDatagrid.datagrid("selectAll");
        return;
      }else{
        logDatagrid.datagrid("unselectAll")
      }
    }
  };

  //4 初始化组件
  //4.1 初始化数据表格
  logDatagrid.datagrid({
    title:'日志列表',
    url:'log/page',
    pagination:true,
    rownumbers:true,
    singleSelect:false,
    fit:true,
    pageList:[20,30,40],
    pageSize:20,
    striped:true,
    checkOnSelect:false,
    fitColumns:true,//列宽度
    columns:[[
      {field:'create_time',title:'创建时间',width:100},
      {field:'logs',title:'日志内容',width:300},
    ]],

    toolbar:'#logDatagridToolbar'
  });

  //5 为页面上的所有的a标签注册点击事件
  $("a").on("click",function(){
    //获取标签的data-cmd属性值
    var cmd = $(this).data("cmd");
    if(cmd){
      cmdObj[cmd+""]();
    }
  });
});
